import numpy as np
import pandas as pd

# 读取Iris数据
iris = pd.read_csv('iris.data', header=None)
X = iris.iloc[:, :-1].values
y = iris.iloc[:, -1].values

# 随机划分训练集（105条）、测试集（45条）
np.random.seed(42)  # 固定随机种子，结果可复现
idx = np.random.permutation(len(X))
X_train, X_test = X[idx[:105]], X[idx[105:]]
y_train, y_test = y[idx[:105]], y[idx[105:]]

# 欧氏距离计算
def euclid_dist(x1, x2):
    return np.sqrt(np.sum((x1 - x2)**2))

# KNN预测函数（k取3）
def knn_predict(x_test, X_train, y_train, k=3):
    dists = [euclid_dist(x_test, x) for x in X_train]
    k_idx = np.argsort(dists)[:k]
    k_labels = [y_train[i] for i in k_idx]
    return max(set(k_labels), key=k_labels.count)

# 批量预测+计算准确率
y_pred = [knn_predict(x, X_train, y_train) for x in X_test]
accuracy = np.sum(y_pred == y_test) / len(y_test)

# 输出结果
print(f'KNN分类准确率：{accuracy:.2%}')
print('\n前5条测试样本预测结果：')
for i in range(5):
    print(f'真实标签：{y_test[i]} | 预测标签：{y_pred[i]}')